<?php


namespace Beerus\Modules\Wiki\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\service\search\AdmUserSearch;
use Doraemon\service\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Biz\service\admin\AdWhiteList as sAdWhiteList;
use App\Exceptions\InputErrorException;

class AdWhiteListController extends Controller
{
    const PAGE_SIZE = 20;
    public function index(Request $request, Content $content)
    {
        $page = $request->input('page', 1);
        $limit = [
            ($page - 1) * self::PAGE_SIZE,
            self::PAGE_SIZE
        ];

        return $content->header('广告曝光套餐白名单管理')
            ->breadcrumb(
                ['text' => '广告曝光套餐白名单管理']
            )->row($this->grid($request->all(), $limit));
    }

    public function update(Request $request, $id = 0)
    {
        $params = $request->all();

        if(!is_numeric($params['shop_id'])) {
            throw new InputErrorException('商家ID只能输入数字', InputErrorException::DEFAULT_CODE, 'shop_id');
        }

        if($params['start_time'] >= $params['end_time']) {
            throw new InputErrorException('开始时间必须小于结束时间', InputErrorException::DEFAULT_CODE, 'start_time');
        }

        $id = sAdWhiteList::update($id, $params, Admin::user()->id);

        if(!$id) {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        } else {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/wiki/adwhitelist/' . $id . '/edit/')->with(compact('success'));
        }
    }

    public function create(Content $content, $id = 0)
    {
        $info = [];
        if($id > 0) {
            $info = sAdWhiteList::getInfo($id);
        }

        $form = new Form($info);
        if($id > 0) {
            $form->text('shop_id', '商家ID')->readonly();
        } else {
            $form->text('shop_id', '商家ID')->required();
        }

        $form->text('shop_name', '商家名称')->readonly();
        $form->datetime('start_time', '开始时间')->required();
        $form->datetime('end_time', '结束时间')->required();
        $form->textarea('remark')->placeholder('备注信息');

        $form->action('/admin/wiki/adwhitelist/update/'. $id);
        Admin::script($this->getBaseInfoScript());
        return $content->header('编辑白名单')
            ->breadcrumb(
                ['text' => '广告曝光套餐白名单管理', 'url' => 'wiki/adwhitelist'],
                ['text' => '编辑白名单']
            )
            ->row($form);
    }

    public function grid($params, $limit)
    {
        $where = $this->buildWhere($params);
        $list = sAdWhiteList::getList($where, $limit);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => self::PAGE_SIZE
        ]);
        return Admin::grid($gridModel, function (Grid $grid) {

            $grid->filter(function ($filter){
                $filter->disableIdFilter();

                $filter->dropDown('wiki_value', [
                    'shop_id' => '商家ID',
                    'shop_name' => '商家名称',
                ]);

                $filter->expand();//默认展开
            });

            $grid->column('id', 'ID');
            $grid->column('shop_id', '商家ID');
            $grid->column('shop_name', '商家名称');
            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('remark', '备注');

            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
            });
        });
    }

    private function buildWhere($params)
    {
        $where = ['whitelist_status' => 1];
        if(isset($params['shop_id']) && $params['shop_id']) {
            $where['shop_id'] = $params['shop_id'];
        }

        if(isset($params['shop_name']) && $params['shop_name']) {
            $results = AdmUserSearch::getUserIdsByFilter(['nick' => $params['shop_name']], 1);
            $where['shop_id'] = $results['rows'];
        }

        return $where;
    }

    public function getBasicInfo(Request $request)
    {
        $shopId = $request->input('shop_id');
        $userInfo = User::getBasicUserInfo($shopId);
        return [
            'code' => 1,
            'msg' => $userInfo ? $userInfo['nick'] : '账号不存在'
        ];
    }

    private function getBaseInfoScript()
    {
        return <<<EOF
$('.shop_id').blur(function(){
    var shop_id = $(this).val();
    var url = 'getbasicinfo?shop_id=' + $(this).val()
    $.get(url, function (result) {
        if (result.code == 1) {
            $('.shop_name').val(result.msg)
        }
    });  
})
EOF;
    }
}